package org.javaboy.sdr_delay_msg_queue.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Set;

@Service
public class DelayMsgQueueService {

    public static final String QUEUE_NAME = "delay-msg";

    @Autowired
    RedisTemplate redisTemplate;

    public void send(String msg, Long delayTime) {
        redisTemplate.opsForZSet().add(QUEUE_NAME, msg, System.currentTimeMillis() + delayTime * 1000);
    }

    @Scheduled(fixedDelay = 500)
    public void receive() {
        Set<String> msgs = redisTemplate.opsForZSet().rangeByScore(QUEUE_NAME, 0, System.currentTimeMillis());
        for (String msg : msgs) {
            if (redisTemplate.opsForZSet().remove(QUEUE_NAME, msg) > 0)
                System.out.println(new Date() + ">>>消费了消息：" + msg);
        }
    }
}
